package com.koujun.meinv.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import org.apache.log4j.Logger;

public class MySql {
	private Connection connection;
	private String username = System.getenv("mysqluser");
	private String password = System.getenv("mysqlpassword");
	private String connName = System.getenv("mysql");

	private static MySql is = null;
	private static Logger LOG = Logger.getLogger(MySql.class);

	public static MySql get() {
		if (is == null) {
			is = new MySql();
		}
		return is;
	}

	public MySql() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(connName, username, password);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void createConn() {
		try {
			this.connection = DriverManager.getConnection(connName, username, password);
			LOG.info("Create connection !" + new Date());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void ex(String sql) throws SQLException {
		checkConn();
		Statement st = this.connection.createStatement();
		st.execute(sql.toString());
		if (st != null)
			st.close();
	}

	public ResultSet exRs(String sql) throws SQLException {
		checkConn();
		ResultSet rs =null;
		try{
			Statement st = this.connection.createStatement();
			rs = st.executeQuery(sql.toString());
		}catch(Exception e){
			LOG.error(e);
		}
		return rs;
	}

	public void checkConn() {
		try {
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT NOW()");
			Statement st = this.connection.createStatement();
			ResultSet rs = st.executeQuery(sql.toString());

			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
		} catch (Exception e) {
			createConn();
		}
	}
}
